package la.bbs558.util;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import la.bbs558.entity.params.UserSignUpParams;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Slf4j
public class ExcelUtil extends cn.hutool.poi.excel.ExcelUtil {

    public static final String DEFAULT_PASSWORD = "123456";

    @SneakyThrows
    public static List<UserSignUpParams> parseExcel2Register(MultipartFile file) {
        List<List<Object>> readList = ExcelUtil.getReader(file.getInputStream()).read();
        if (readList.size() <= 1) {
            log.info("没有解析到内容呢");
            return Collections.emptyList();
        }
        List<UserSignUpParams> userSignUpParamsList = new ArrayList<>(readList.size() - 1);
        for (int i = 1, readListSize = readList.size(); i < readListSize; i++) {
            List<Object> row = readList.get(i);
            log.info("解析到row-{}:{}", i, JSON.toJSONString(row));
            if (row.size() < 4) {
                continue;
            }
            //第二行开始解析
            UserSignUpParams userSignUpParams = new UserSignUpParams();
            Object cell1 = row.get(0);
            Object cell2 = row.get(1);
            Object cell3 = row.get(2);
            Object cell4 = row.get(3);
            String email = Objs.getOrElse(cell1, "").toString();
            String nickname = Objs.getOrElse(cell2, "").toString();
            String tel = Objs.getOrElse(cell3, "").toString();
            String sign = Objs.getOrElse(cell4, "").toString();
            userSignUpParams.setEmail(email);
            userSignUpParams.setUsername(email);
            userSignUpParams.setNickname(nickname);
            userSignUpParams.setPassword(SecureUtil.md5(DEFAULT_PASSWORD));
            userSignUpParams.setTel(tel);
            userSignUpParams.setSign(sign);
            userSignUpParams.setAvatar(getAvatar());
            userSignUpParamsList.add(userSignUpParams);
        }
        return userSignUpParamsList;
    }

    @NotNull
    private static String getAvatar() {
        return "user/" + RandomUtil.randomInt(1, 501) + ".jpeg";
    }
}
